package com.smartcruise.util.network.netUtils;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.smartcruise.base.BaseNormalView;
import com.smartcruise.base.RefreshContract;
import com.smartcruise.data.Contacts;
import com.smartcruise.data.PageHistory;
import com.smartcruise.data.PushData;
import com.smartcruise.data.ReportData;
import com.smartcruise.data.SavedLocation;
import com.smartcruise.data.cruiseData.CruiseContract;
import com.smartcruise.data.cruiseData.CruiseData;
import com.smartcruise.data.cruiseData.ReportType;
import com.smartcruise.util.Key;
import com.smartcruise.util.ListUtils;
import com.smartcruise.util.TempleUser;
import com.smartcruise.util.TimeUtils;
import com.smartcruise.util.Utils;
import com.smartcruise.util.network.BaseRequest;
import com.smartcruise.util.network.baseApi.NetApiObservableFactory;
import com.smartcruise.util.network.callBack.BaseCallBack;
import com.smartcruise.util.network.customerObserver.CustomDoOnNext;
import com.smartcruise.util.network.customerObserver.SimpleBackObserver;
import com.smartcruise.util.network.customerObserver.SimpleProgressObserverImp;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.functions.Consumer;
import io.realm.Realm;
import io.realm.RealmResults;

/**
 * Created by FengChaoQun
 * on 2018/2/5 0005
 * 网络请求API入口
 */

public class NetCollection {

    public static void login(String account, String password, final BaseNormalView baseNormalView, BaseCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put(Key.userName, account);
        map.put(Key.passWord, password);
        map.put("deviceId", Utils.getAndroidId());

        BaseRequest.normalPost(BaseUrl.LOGIN, map, baseNormalView, callBack);
    }

    /**
     * description:获取联系人列表
     */

    public static void getContacts(final RefreshContract.View baseNormalView, BaseCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put(Key.id, TempleUser.getInstance().getAccount());

        BaseRequest.normalPostRefresh(BaseUrl.GET_CONTACTS, map, baseNormalView, callBack, new Consumer<Result>() {
            @Override
            public void accept(final Result result) throws Exception {
                if (!NetContract.isSuccess(result)) {
                    return;
                }
                try (Realm realm = Realm.getDefaultInstance()) {
                    realm.executeTransaction(new Realm.Transaction() {
                        @Override
                        public void execute(Realm realm) {
                            try {
                                //先删除本地数据
                                realm.where(Contacts.class).findAll().deleteAllFromRealm();

                                //保存一般联系人
                                JSONObject jsonObject = new JSONObject(result.getData());
                                realm.createOrUpdateAllFromJson(Contacts.class, jsonObject.getJSONArray("generalContactList"));

                                //保存紧急联系人
                                Gson gson = new Gson();
                                List<Contacts> contacts = gson.fromJson(jsonObject.getString("emergencyContactList"),
                                        new TypeToken<List<Contacts>>() {
                                        }.getType());
                                if (ListUtils.isHaveContent(contacts)) {
                                    for (Contacts contacts1 : contacts) {
                                        contacts1.setEmergency(true);
                                    }
                                    realm.copyToRealmOrUpdate(contacts);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        });
    }

    /**
     * description:上传当前一个位置信息
     */

    public static void pushLocation(final String latitude, final String longitude) {
        String patrollingTaskId = null;
        try (Realm realm = Realm.getDefaultInstance()) {
            CruiseData first = realm.where(CruiseData.class)
                    .equalTo(Key.inspectorId, TempleUser.getInstance().getAccount())
                    .equalTo(Key.isCopyData, true)
                    .equalTo(Key.isFromNet, false)
                    .equalTo(Key.statusInApp, CruiseContract.TASK_IS_RUNNING)
                    .findFirst();
            if (first != null) {
                patrollingTaskId = first.getPatrollingTaskId();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("longitude", longitude);
        map.put("latitude", latitude);
        map.put(Key.id, TempleUser.getInstance().getAccount());
        if (!TextUtils.isEmpty(patrollingTaskId)) {
            map.put(Key.patrollingTaskId, patrollingTaskId);
        }

        final String finalPatrollingTaskId = patrollingTaskId;
        BaseRequest.normalPostBack(BaseUrl.PUSH_LOCATION, map, new BaseCallBack() {
            @Override
            public void onSuccess(Result result) {
                Log.d("NetCollection", "上传位置成功");
            }

            @Override
            public void onFail(Result result) {
                saveLocation(latitude, longitude, finalPatrollingTaskId);
            }

            @Override
            public void onError(Throwable e) {
                saveLocation(latitude, longitude, finalPatrollingTaskId);
                e.printStackTrace();
            }
        });
    }

    /**
     * description:将一个位置信息存储到本地
     */

    private static void saveLocation(final String latitude, final String longitude, final String patrollingTaskId) {
        try (Realm realm = Realm.getDefaultInstance()) {
            realm.executeTransactionAsync(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    SavedLocation savedLocation = realm.createObject(SavedLocation.class);
                    savedLocation.setEmployeeUserId(TempleUser.getInstance().getAccount());
                    savedLocation.setLatitude(latitude);
                    savedLocation.setLongitude(longitude);
                    savedLocation.setTime(System.currentTimeMillis());
                    savedLocation.setPatrollingTaskId(patrollingTaskId);
                }
            });
            Log.d("NetCollection", "存储位置到本地成功");
        }
    }

    public static void pushLocations(String data, BaseCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put("jsonStr", data);

        BaseRequest.normalPostBack(BaseUrl.PUSH_LOCATIONS, map, callBack);
    }

    /**
     * description:获取所有原任务
     */

    public static void getAllTask(RefreshContract.View baseNormalView, BaseCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", TempleUser.getInstance().getAccount());

        BaseRequest.normalPostRefresh(BaseUrl.GET_ALL_TASK, map, baseNormalView, callBack, new Consumer<Result>() {
            @Override
            public void accept(final Result result) throws Exception {
                if (!NetContract.isSuccess(result)) {
                    return;
                }
                try (Realm realm = Realm.getDefaultInstance()) {
                    realm.executeTransaction(new Realm.Transaction() {
                        @Override
                        public void execute(Realm realm) {
                            //先删除本地原任务
                            realm.where(CruiseData.class)
                                    .equalTo(Key.isCopyData, false)
                                    .equalTo(Key.isFromNet, false)
                                    .findAll().deleteAllFromRealm();

                            realm.createOrUpdateAllFromJson(CruiseData.class, result.getData());
                        }
                    });
                }
                //更新数据库
                CruiseContract.refreshLocalDataBase();
            }
        });
    }

    /**
     * description:获取一个指定的原任务
     */

    public static void getOneNewTask(BaseNormalView baseNormalView, String id, BaseCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);

        BaseRequest.normalPost(BaseUrl.GET_TASK, map, baseNormalView, callBack, new Consumer<Result>() {
            @Override
            public void accept(Result result) throws Exception {
                if (NetContract.isSuccess(result)) {
                    CruiseContract.saveOneNewTask(result);
                }
            }
        });
    }

    /**
     * description:获取指定的原任务 不显示加载框
     */

    public static void getOneNewTaskBack(String id) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);

        BaseRequest.normalPostBack(BaseUrl.GET_TASK, map, new BaseCallBack() {
            @Override
            public void onSuccess(Result result) {
                Log.d("PushReceiver", "刷新新任务成功");
            }

            @Override
            public void onFail(Result result) {
                Log.d("PushReceiver", "" + result.getMessage());
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }
        }, new Consumer<Result>() {
            @Override
            public void accept(Result result) throws Exception {
                if (NetContract.isSuccess(result)) {
                    CruiseContract.saveOneNewTask(result);
                }
            }
        });
    }

    /**
     * description:获取一个指定的已审核任务
     */

    public static void getOneAuditedTask(String id, BaseNormalView baseNormalView, BaseCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);

        BaseRequest.normalPost(BaseUrl.GET_ONE_AUDITED_TASK, map, baseNormalView, callBack, new Consumer<Result>() {
            @Override
            public void accept(Result result) throws Exception {
                if (NetContract.isSuccess(result)) {
                    try (Realm realm = Realm.getDefaultInstance()) {
                        final JSONObject jsonObject = new JSONObject(result.getData());
                        realm.executeTransaction(new Realm.Transaction() {
                            @Override
                            public void execute(Realm realm) {
                                try {
                                    CruiseContract.saveArchiveTask(jsonObject, realm);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                }
            }
        });
    }

    /**
     * description:获取一个指定的已审核任务 不显示加载框
     */

    public static void getOneAuditedTaskBack(String id) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);

        BaseRequest.normalPostBack(BaseUrl.GET_ONE_AUDITED_TASK, map, new BaseCallBack() {
            @Override
            public void onSuccess(Result result) {
                Log.d("PushReceiver", "刷新已审核的任务成功");
            }

            @Override
            public void onFail(Result result) {
                Log.d("PushReceiver", "" + result.getMessage());
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }
        }, new Consumer<Result>() {
            @Override
            public void accept(Result result) throws Exception {
                if (NetContract.isSuccess(result)) {
                    try (Realm realm = Realm.getDefaultInstance()) {
                        final JSONObject jsonObject = new JSONObject(result.getData());
                        realm.executeTransaction(new Realm.Transaction() {
                            @Override
                            public void execute(Realm realm) {
                                try {
                                    CruiseContract.saveArchiveTask(jsonObject, realm);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                }
            }
        });
    }

    /**
     * description:获取一个指定的已审核通报
     */

    public static void getOneAuditedReport(String id, BaseNormalView baseNormalView, BaseCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);

        BaseRequest.normalPost(BaseUrl.GET_ONE_AUDITED_REPORT, map, baseNormalView, callBack, new Consumer<Result>() {
            @Override
            public void accept(final Result result) throws Exception {
                if (NetContract.isSuccess(result)) {
                    try (Realm realm = Realm.getDefaultInstance()) {
                        realm.executeTransaction(new Realm.Transaction() {
                            @Override
                            public void execute(Realm realm) {
                                try {
                                    JSONObject jsonObject = new JSONObject(result.getData());
                                    CruiseContract.saveOneArchiveReportData(jsonObject, realm);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                }
            }
        });
    }

    /**
     * description:获取一个指定的已审核通报 不显示加载框
     */

    public static void getOneAuditedReportBack(String id) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);

        BaseRequest.toSubscribe(NetApiObservableFactory.getInstance().normalPostObservable(BaseUrl.GET_ONE_AUDITED_REPORT, map),
                new SimpleBackObserver(new BaseCallBack() {
                    @Override
                    public void onSuccess(Result result) {
                        Log.d("PushReceiver", "刷新已审核的通报成功");
                    }

                    @Override
                    public void onFail(Result result) {
                        Log.d("PushReceiver", "" + result.getMessage());
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }
                }), new Consumer<Result>() {
                    @Override
                    public void accept(final Result result) throws Exception {//保存数据到本地
                        try (Realm realm = Realm.getDefaultInstance()) {
                            if (NetContract.isSuccess(result)) {
                                realm.executeTransaction(new Realm.Transaction() {
                                    @Override
                                    public void execute(Realm realm) {
                                        JSONObject jsonObject = null;
                                        try {
                                            jsonObject = new JSONObject(result.getData());
                                            CruiseContract.saveOneArchiveReportData(jsonObject, realm);
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                            }
                        }
                    }
                });
    }

    public static void pushTask(String data, BaseNormalView baseNormalView, BaseCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put("jsonString", data);

        BaseRequest.toSubscribe(NetApiObservableFactory.getInstance().normalPostObservable(BaseUrl.PUSH_TASK, map),
                new SimpleProgressObserverImp(baseNormalView, callBack));
    }

    public static void pushTask2(String data, Observer<Result> observer) {
        Map<String, Object> map = new HashMap<>();
        map.put("jsonString", data);

        BaseRequest.toSubscribe(NetApiObservableFactory.getInstance().normalPostObservable(BaseUrl.PUSH_TASK, map),
                observer);
    }

    /**
     * description:上传通报数据
     *
     * @param data json字符串
     */

    public static void pushReport(String data, Observer<Result> observer) {
        Map<String, Object> map = new HashMap<>();
        map.put("jsonString", data);

        BaseRequest.toSubscribe(NetApiObservableFactory.getInstance().normalPostObservable(BaseUrl.PUSH_REPORT, map),
                observer);
    }

    /**
     * description:分页加载已完成的任务
     *
     * @param pageNumber 加载的当前页数
     */

    public static void getCompletedTask(final int pageNumber, RefreshContract.View baseNormalView, BaseCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", TempleUser.getInstance().getAccount());
        map.put("pageNumber", pageNumber);
        map.put("pageSize", PageHistory.pageSize);

        BaseRequest.normalPostRefresh(BaseUrl.GET_COMPLETED_TASK, map, baseNormalView, callBack, new Consumer<Result>() {
            @Override
            public void accept(Result result) throws Exception {
                if (!NetContract.isSuccess(result)) {
                    return;
                }

                final JSONObject jsonObject = new JSONObject(result.getData());
                final long totalNumber = jsonObject.getLong("totalNumber");
                try (Realm realm = Realm.getDefaultInstance()) {
                    final PageHistory pageHistory = realm.where(PageHistory.class)
                            .equalTo(Key.userId, TempleUser.getInstance().getAccount())
                            .equalTo(Key.type, PageHistory.TYPE_COMPLETED_TASK)
                            .findFirst();
                    realm.executeTransaction(new Realm.Transaction() {
                        @Override
                        public void execute(Realm realm) {
                            if (pageHistory != null) {
                                pageHistory.setCurrentPage(pageNumber);
                                pageHistory.setTotalNumber(totalNumber);
                                if (pageNumber == 1) {
                                    pageHistory.setLastRefreshTime(TimeUtils.currentTime());
                                    //删除本地已存在的已完成的任务
                                    realm.where(CruiseData.class)
                                            .equalTo(Key.auditStatus, CruiseContract.AUDITED)
                                            .equalTo(Key.auditResult, CruiseContract.AUDIT_SUCCESS)
                                            .findAll().deleteAllFromRealm();
                                }
                            }
                        }
                    });
                }

                final JSONArray patrollingTaskEntityList = jsonObject.getJSONArray("patrollingTaskEntityList");
                CruiseContract.saveArchiveTasks(patrollingTaskEntityList);
            }
        });
    }

    /**
     * description:后台加载被驳回的任务
     */

    public static void getFailedTaskBack(BaseCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", TempleUser.getInstance().getAccount());

        BaseRequest.normalPostBack(BaseUrl.GET_FAILED_TASK, map, callBack, new Consumer<Result>() {
            @Override
            public void accept(Result result) throws Exception {
                if (!NetContract.isSuccess(result)) {
                    return;
                }

                //删除本地已存在的且不需要保存的被驳回的任务
                try (Realm realm = Realm.getDefaultInstance()) {
                    realm.executeTransaction(new Realm.Transaction() {
                        @Override
                        public void execute(Realm realm) {
                            realm.where(CruiseData.class)
                                    .equalTo(Key.isFromNet, true)
                                    .equalTo(Key.auditStatus, CruiseContract.AUDITED)
                                    .equalTo(Key.auditResult, CruiseContract.AUDIT_FAIL)
                                    .not()
                                    .beginGroup()
                                    .equalTo(Key.dataChanged, true)
                                    .equalTo(Key.uploadStatus, 0)
                                    .endGroup()
                                    .findAll().deleteAllFromRealm();
                        }
                    });
                }

                final JSONArray patrollingTaskEntityList = new JSONArray(result.getData());
                CruiseContract.saveArchiveTasks(patrollingTaskEntityList);
            }
        });
    }

    /**
     * description:分页加载推送记录
     *
     * @param pageNumber 加载的当前页数
     */

    public static void getPushHistory(final int pageNumber, RefreshContract.View baseNormalView, BaseCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", TempleUser.getInstance().getAccount());
        map.put("pageNumber", pageNumber);
        map.put("pageSize", PageHistory.pageSize);

        BaseRequest.normalPostRefresh(BaseUrl.GET_PUSH_HISTORY, map, baseNormalView, callBack, new Consumer<Result>() {
            @Override
            public void accept(Result result) throws Exception {
                if (!NetContract.isSuccess(result)) {
                    return;
                }
                final JSONObject jsonObject = new JSONObject(result.getData());
                final long totalNumber = jsonObject.getLong("totalNumber");
                try (Realm realm = Realm.getDefaultInstance()) {
                    realm.executeTransaction(new Realm.Transaction() {
                        @Override
                        public void execute(Realm realm) {
                            if (pageNumber == 1) {//下拉刷新的时候 清空本地数据
                                realm.where(PushData.class).findAll().deleteAllFromRealm();
                            }
                            try {
                                realm.createOrUpdateAllFromJson(PushData.class, jsonObject.getString("entityList"));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });

                    final PageHistory pageHistory = realm.where(PageHistory.class)
                            .equalTo(Key.userId, TempleUser.getInstance().getAccount())
                            .equalTo(Key.type, PageHistory.TYPE_NOTICE)
                            .findFirst();
                    realm.executeTransaction(new Realm.Transaction() {
                        @Override
                        public void execute(Realm realm) {
                            if (pageHistory != null) {
                                pageHistory.setCurrentPage(pageNumber);
                                pageHistory.setTotalNumber(totalNumber);
                                if (pageNumber == 1) {
                                    pageHistory.setLastRefreshTime(TimeUtils.currentTime());
                                }
                            }
                        }
                    });
                }
            }
        });
//        BaseRequest.toSubscribe(NetApiObservableFactory.getInstance().normalPostObservable(BaseUrl.GET_PUSH_HISTORY, map),
//                new SimpleProgressObserverImp(baseNormalView, callBack), new Consumer<Result>() {
//                    @Override
//                    public void accept(final Result result) throws Exception {//保存数据到本地
//                        if (!NetContract.isSuccess(result)) {
//                            return;
//                        }
//                        final JSONObject jsonObject = new JSONObject(result.getData());
//                        final long totalNumber = jsonObject.getLong("totalNumber");
//                        try (Realm realm = Realm.getDefaultInstance()) {
//                            realm.executeTransaction(new Realm.Transaction() {
//                                @Override
//                                public void execute(Realm realm) {
//                                    if (pageNumber == 1) {//下拉刷新的时候 清空本地数据
//                                        realm.where(PushData.class).findAll().deleteAllFromRealm();
//                                    }
//                                    try {
//                                        realm.createOrUpdateAllFromJson(PushData.class, jsonObject.getString("entityList"));
//                                    } catch (JSONException e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//                            });
//
//                            final PageHistory pageHistory = realm.where(PageHistory.class)
//                                    .equalTo(Key.userId, TempleUser.getInstance().getAccount())
//                                    .equalTo(Key.type, PageHistory.TYPE_NOTICE)
//                                    .findFirst();
//                            realm.executeTransaction(new Realm.Transaction() {
//                                @Override
//                                public void execute(Realm realm) {
//                                    if (pageHistory != null) {
//                                        pageHistory.setCurrentPage(pageNumber);
//                                        pageHistory.setTotalNumber(totalNumber);
//                                        if (pageNumber == 1) {
//                                            pageHistory.setLastRefreshTime(TimeUtils.currentTime());
//                                        }
//                                    }
//                                }
//                            });
//                        }
//                    }
//                });
    }

    /**
     * description:分页加载通报记录
     *
     * @param pageNumber 加载的当前页数
     */

    public static void getReportDataHistory(final int pageNumber, RefreshContract.View baseNormalView, BaseCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", TempleUser.getInstance().getAccount());
        map.put("pageNumber", pageNumber);
        map.put("pageSize", PageHistory.pageSize);

        BaseRequest.normalPostRefresh(BaseUrl.GET_REPORT_HISTORY, map, baseNormalView, callBack, new Consumer<Result>() {
            @Override
            public void accept(Result result) throws Exception {
                if (!NetContract.isSuccess(result)) {
                    return;
                }

                final JSONObject jsonObject = new JSONObject(result.getData());
                final long totalNumber = jsonObject.getLong("totalNumber");
                try (Realm realm = Realm.getDefaultInstance()) {
                    final PageHistory pageHistory = realm.where(PageHistory.class)
                            .equalTo(Key.userId, TempleUser.getInstance().getAccount())
                            .equalTo(Key.type, PageHistory.TYPE_REPORT)
                            .findFirst();
                    realm.executeTransaction(new Realm.Transaction() {
                        @Override
                        public void execute(Realm realm) {
                            if (pageHistory != null) {
                                pageHistory.setCurrentPage(pageNumber);
                                pageHistory.setTotalNumber(totalNumber);
                                if (pageNumber == 1) {
                                    pageHistory.setLastRefreshTime(TimeUtils.currentTime());
                                    //删除本地的网络通报记录
                                    //排除已经修改过的 且还未上传的数据
                                    realm.where(ReportData.class)
                                            .equalTo(Key.isFromNet, true)
                                            .not()
                                            .beginGroup()
                                            .equalTo(Key.dataChanged, true)
                                            .equalTo(Key.auditStatus, 0)
                                            .endGroup()
                                            .findAll().deleteAllFromRealm();
                                }
                            }
                        }
                    });
                }

                CruiseContract.saveReportData(result);
            }
        });
    }

    /**
     * description:发送手机验证码
     */

    public static void sendPhoneVerifyCode(String phone, BaseNormalView baseNormalView, BaseCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put(Key.phoneNumber, phone);

        BaseRequest.normalPost(BaseUrl.SEND_PHONE_VERIFY_CODE, map, baseNormalView, callBack);
    }

    /**
     * description:验证手机验证码
     */

    public static void checkCode(String phone, String code, BaseNormalView baseNormalView, BaseCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put(Key.phoneNumber, phone);
        map.put("verificationCode", code);

        BaseRequest.normalPost(BaseUrl.CHECK_CODE, map, baseNormalView, callBack);
    }

    /**
     * description:找回密码
     */

    public static void findPassword(String phone, String password, BaseNormalView baseNormalView, BaseCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put(Key.phoneNumber, phone);
        map.put("passWord", password);

        BaseRequest.normalPost(BaseUrl.FIND_PASSWORD, map, baseNormalView, callBack);
    }

    /**
     * description:修改密码
     */

    public static void checkPassword(String password, BaseNormalView baseNormalView, BaseCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put(Key.id, TempleUser.getInstance().getAccount());
        map.put("passWord", password);

        BaseRequest.normalPost(BaseUrl.CHECK_PASSWORD, map, baseNormalView, callBack);
    }

    /**
     * description:修改密码
     */

    public static void modifyPassword(String password, BaseNormalView baseNormalView, BaseCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put(Key.id, TempleUser.getInstance().getAccount());
        map.put("passWord", password);

        BaseRequest.normalPost(BaseUrl.MODIFY_PASSWORD, map, baseNormalView, callBack);
    }

    /**
     * description:撤回任务成功回传
     */

    public static void revokeTaskOk(String taskId, BaseCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put(Key.id, taskId);
        map.put(Key.status, "已撤销");

        BaseRequest.normalPostBack(BaseUrl.REVOKE_TASK_OK, map, callBack);
    }

    /**
     * description:获取通报类型
     * 1.先从本地查找 若是本地存在 则返回成功 且在后台刷新数据
     * 2.如果本地不存在 则去服务器获取
     */

    public static void getReportType(BaseNormalView baseNormalView, BaseCallBack callBack) {
        RealmResults<ReportType> all = baseNormalView.getRealm().where(ReportType.class).findAll();
        if (all.isEmpty()) {
            getReportTypeFromNet(baseNormalView, callBack);
        } else {
            callBack.onSuccess(null);
            getReportTypeBack(new BaseCallBack() {
                @Override
                public void onSuccess(Result result) {

                }

                @Override
                public void onFail(Result result) {

                }

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                }
            });
        }
    }

    public static void getReportTypeFromNet(BaseNormalView baseNormalView, BaseCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put("key", "NotifiedEventType");

        BaseRequest.normalPost(BaseUrl.GET_TYPE, map, baseNormalView, callBack, new CustomDoOnNext(true) {
            @Override
            public void accept(final Result result) throws Exception {
                if (NetContract.isSuccess(result)) {
                    try (Realm realm = Realm.getDefaultInstance()) {
                        realm.executeTransaction(new Realm.Transaction() {
                            @Override
                            public void execute(Realm realm) {
                                realm.where(ReportType.class).findAll().deleteAllFromRealm();
                                realm.createOrUpdateAllFromJson(ReportType.class, result.getData());
                            }
                        });
                    }
                }
            }
        });
    }

    public static void getReportTypeBack(BaseCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put("key", "NotifiedEventType");

        BaseRequest.normalPostBack(BaseUrl.GET_TYPE, map, callBack, new CustomDoOnNext(true) {
            @Override
            public void accept(final Result result) throws Exception {
                if (NetContract.isSuccess(result)) {
                    try (Realm realm = Realm.getDefaultInstance()) {
                        realm.executeTransaction(new Realm.Transaction() {
                            @Override
                            public void execute(Realm realm) {
                                realm.where(ReportType.class).findAll().deleteAllFromRealm();
                                realm.createOrUpdateAllFromJson(ReportType.class, result.getData());
                            }
                        });
                    }
                }
            }
        });
    }

    public static void getContacts(BaseNormalView baseNormalView, BaseCallBack callBack) {
        RealmResults<Contacts> allContacts = baseNormalView.getRealm().where(Contacts.class)
                .equalTo("auditor", "是")
                .not().equalTo(Key.id, TempleUser.getInstance().getAccount())
                .findAll();
        if (allContacts.isEmpty()) {
            getContactsFromNet(baseNormalView, callBack);
        } else {
            callBack.onSuccess(null);
        }
    }

    public static void getContactsFromNet(BaseNormalView baseNormalView, BaseCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put(Key.id, TempleUser.getInstance().getAccount());

        BaseRequest.normalPost(BaseUrl.GET_CONTACTS, map, baseNormalView, callBack, new Consumer<Result>() {
            @Override
            public void accept(final Result result) throws Exception {
                if (!NetContract.isSuccess(result)) {
                    return;
                }
                try (Realm realm = Realm.getDefaultInstance()) {
                    realm.executeTransaction(new Realm.Transaction() {
                        @Override
                        public void execute(Realm realm) {
                            try {
                                //先删除本地数据
                                realm.where(Contacts.class).findAll().deleteAllFromRealm();

                                //保存一般联系人
                                JSONObject jsonObject = new JSONObject(result.getData());
                                realm.createOrUpdateAllFromJson(Contacts.class, jsonObject.getJSONArray("generalContactList"));

                                //保存紧急联系人
                                Gson gson = new Gson();
                                List<Contacts> contacts = gson.fromJson(jsonObject.getString("emergencyContactList"),
                                        new TypeToken<List<Contacts>>() {
                                        }.getType());
                                if (ListUtils.isHaveContent(contacts)) {
                                    for (Contacts contacts1 : contacts) {
                                        contacts1.setEmergency(true);
                                    }
                                    realm.copyToRealmOrUpdate(contacts);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        });
    }

}
